<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Props</title>
  <!--  引入React核心库-->
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <!--  引入react-dom,用于支持React操作Dom-->
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <!-- 引入babel，用于将jsx转为js-->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script src="https://unpkg.com/prop-types@15.6.2/prop-types.js"></script>

</head>

<body>
  <div id="root1"></div>
  <div id="root2"></div>
  <script type="text/babel">
    // 1.创建组件
    class Person extends React.Component {
      render() {
        // props是只读的
        // this.props.name = 'jack' // 此行代码会报错，因为props是只读的
        const { name, age, sex } = this.props
        return (
          <ul>
            <li>姓名：{name}</li>
            <li>年龄：{age + 1}</li>
            <li>性别：{sex}</li>
          </ul>)
      }
    }
    // 对标签属性进行类型，必要性的限制
    Person.propTypes = {
      name: PropTypes.string.isRequired, // 限制name必填，且为字符串
      sex: PropTypes.string, // 限制为字符串
      age: PropTypes.number, // 限制age为数值
      speak: PropTypes.func // 限制speak为函数
    }
    // 指定默认的标签属性值
    Person.defaultProps = {
      sex: '男', // sex默认值为男
      age: 18 // age默认值为18
    }
    // 2.渲染组件
    const container1 = document.getElementById('root1')
    const container2 = document.getElementById('root2')
    const root1 = ReactDOM.createRoot(container1)
    const root2 = ReactDOM.createRoot(container2)
    root1.render(<Person name="小明" age={18} sex="男" />)
    // const p = { name: '小红', age: 20, sex: "" }
    // const p = { name: 100, age: 20, sex: "" }
    // const p = { age: 20, sex: "" }
    const p = { name: '小红', age: 20, speak:speak}
    // root2.render(<Person  name={p.name} age={p.age} sex={p.sex}/>)
    // 语法糖写法
    root2.render(<Person {...p} />)

    function speak(){
      console.log('我说话了');
    }
  </script>
</body>

</html>